package com.example.server.web.exception;

import com.example.server.web.domain.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 客户端错误
     */
    @ExceptionHandler(CustomException.class)
    public RespBean customExceptionHandler(CustomException e, HttpServletRequest request){
        String message = e.getMessage();
        e.printStackTrace();
        return  RespBean.error(401,message,null);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public RespBean handleBindException(BindException e) {
        log.error(e.getMessage(), e);
        //e.printStackTrace();
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return RespBean.error(401,message,null);
    }
}
